import type { I18n as VueI18n, Locale } from 'vue-i18n';
import { createI18n } from 'vue-i18n';
import { DEFAULT_LANGUAGE } from '@/common/utils/constants';
import { getLanguageFromClient } from '@/common/utils/language';

function loadLanguage(prefix: string) {
  const lang = import.meta.glob('@/common/locales/*.y(a)?ml', {
    eager: true,
    import: 'default',
  }) as Record<string, any>;
  const re = new RegExp(`/${prefix}\.`, 'i');
  const key = Object.keys(lang).find(item => item.match(re)) as string;

  return lang[key];
}

export type I18n = VueI18n<NonNullable<unknown>, NonNullable<unknown>, NonNullable<unknown>, Locale, false>;

const i18n = createI18n({
  locale: getLanguageFromClient(),
  fallbackLocale: {
    'en-US': [DEFAULT_LANGUAGE],
  },
  legacy: false,
  allowComposition: true,
  messages: {
    'zh-CN': {
      ...loadLanguage('zh-CN'),
    },
    'en-US': {
      ...loadLanguage('en-US'),
    },
  },
}) as I18n;

export default i18n;
